<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org" 
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layout/base}">
<head>
    <title>智能点餐 - 智能营养管理系统</title>
</head>
<body>
    <div layout:fragment="content">
        <!-- 页面标题和搜索 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-utensils me-2"></i>智能点餐</h2>
            <div class="d-flex align-items-center gap-3">
                <!-- 搜索框 -->
                <div class="input-group" style="width: 300px;">
                    <input type="text" class="form-control" id="searchInput" 
                           placeholder="搜索菜品..." th:value="${currentKeyword}">
                    <button class="btn btn-outline-secondary" type="button" onclick="searchDishes()">
                        <i class="fas fa-search"></i>
                    </button>
                </div>
                <!-- 购物车 -->
                <button class="btn btn-primary position-relative" data-bs-toggle="modal" data-bs-target="#cartModal">
                    <i class="fas fa-shopping-cart"></i>
                    <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger" 
                          id="cartCount" style="display: none;">0</span>
                </button>
            </div>
        </div>

        <!-- 分类导航 -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex flex-wrap gap-2">
                            <a th:href="@{/meals}" 
                               class="btn btn-outline-primary"
                               th:classappend="${currentCategoryId == null ? 'active' : ''}">
                                <i class="fas fa-th-large me-1"></i>全部
                            </a>
                            <a th:each="category : ${categories}"
                               th:href="@{/meals(categoryId=${category.id})}"
                               class="btn btn-outline-primary"
                               th:classappend="${currentCategoryId == category.id ? 'active' : ''}"
                               th:text="${category.name}">分类</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 快速餐别导航 -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="meal-type-nav">
                    <div class="row">
                        <div class="col-lg-3 col-md-6 mb-2">
                            <a th:href="@{/meals/breakfast}" class="btn btn-outline-warning w-100">
                                <i class="fas fa-sun me-2"></i>早餐
                                <small class="d-block">7:00-10:00</small>
                            </a>
                        </div>
                        <div class="col-lg-3 col-md-6 mb-2">
                            <a th:href="@{/meals/lunch}" class="btn btn-outline-primary w-100">
                                <i class="fas fa-sun me-2"></i>午餐
                                <small class="d-block">11:00-14:00</small>
                            </a>
                        </div>
                        <div class="col-lg-3 col-md-6 mb-2">
                            <a th:href="@{/meals/dinner}" class="btn btn-outline-success w-100">
                                <i class="fas fa-moon me-2"></i>晚餐
                                <small class="d-block">17:00-20:00</small>
                            </a>
                        </div>
                        <div class="col-lg-3 col-md-6 mb-2">
                            <a th:href="@{/meals/snacks}" class="btn btn-outline-info w-100">
                                <i class="fas fa-cookie-bite me-2"></i>小食
                                <small class="d-block">随时</small>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- 菜品列表 -->
            <div class="col-lg-9">
                <!-- 热门推荐 -->
                <div th:if="${!popularDishes.empty}" class="mb-4">
                    <h4 class="mb-3">
                        <i class="fas fa-fire text-danger me-2"></i>热门推荐
                    </h4>
                    <div class="row">
                        <div th:each="dish : ${popularDishes}" class="col-lg-4 col-md-6 mb-3">
                            <div class="card h-100 dish-card border-warning">
                                <div class="card-header bg-warning text-dark text-center py-1">
                                    <small><i class="fas fa-fire me-1"></i>热门</small>
                                </div>
                                <div class="card-img-top bg-light d-flex align-items-center justify-content-center" style="height: 150px;">
                                    <i class="fas fa-utensils fa-2x text-muted"></i>
                                </div>
                                <div class="card-body p-3">
                                    <h6 class="card-title mb-1" th:text="${dish.name}">菜品名称</h6>
                                    <div class="nutrition-info mb-2">
                                        <div class="row text-center">
                                            <div class="col-6">
                                                <small class="text-muted">卡路里</small>
                                                <div class="fw-bold small" th:text="${#numbers.formatDecimal(dish.calories, 0, 0)}">0</div>
                                            </div>
                                            <div class="col-6">
                                                <small class="text-muted">蛋白质</small>
                                                <div class="fw-bold small" th:text="${#numbers.formatDecimal(dish.protein, 1, 1)} + 'g'">0g</div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="d-flex justify-content-between align-items-center">
                                        <span class="fw-bold text-primary" th:text="'¥' + ${dish.price}">¥0</span>
                                        <button class="btn btn-warning btn-sm"
                                                th:onclick="'addToCart(' + ${dish.id} + ', \'' + ${dish.name} + '\', ' + ${dish.calories} + ', ' + ${dish.price} + ')'">
                                            <i class="fas fa-plus"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 菜品网格 -->
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h4 class="mb-0">
                        <span th:if="${currentCategoryId != null}">
                            <span th:text="${categories.?[id == __${currentCategoryId}__][0]?.name}">分类</span>菜品
                        </span>
                        <span th:unless="${currentCategoryId != null}">全部菜品</span>
                    </h4>
                    <div class="d-flex align-items-center gap-2">
                        <span class="text-muted">共 <span th:text="${dishPage.totalElements}">0</span> 道菜品</span>
                        <div class="btn-group btn-group-sm" role="group">
                            <button type="button" class="btn btn-outline-secondary active" onclick="setViewMode('grid')">
                                <i class="fas fa-th"></i>
                            </button>
                            <button type="button" class="btn btn-outline-secondary" onclick="setViewMode('list')">
                                <i class="fas fa-list"></i>
                            </button>
                        </div>
                    </div>
                </div>

                <div id="dishGrid" class="row">
                    <div th:each="dish : ${dishPage.content}" class="col-lg-4 col-md-6 mb-4">
                        <div class="card h-100 dish-card">
                            <div class="card-img-top bg-light d-flex align-items-center justify-content-center" style="height: 200px;">
                                <i class="fas fa-utensils fa-3x text-muted"></i>
                            </div>
                            <div class="card-body">
                                <h6 class="card-title" th:text="${dish.name}">菜品名称</h6>
                                <p class="card-text text-muted small" th:text="${dish.description}">菜品描述</p>

                                <!-- 营养信息 -->
                                <div class="nutrition-info mb-2">
                                    <div class="row text-center">
                                        <div class="col-3">
                                            <small class="text-muted">卡路里</small>
                                            <div class="fw-bold small" th:text="${#numbers.formatDecimal(dish.calories, 0, 0)}">0</div>
                                        </div>
                                        <div class="col-3">
                                            <small class="text-muted">蛋白质</small>
                                            <div class="fw-bold small" th:text="${#numbers.formatDecimal(dish.protein, 1, 1)} + 'g'">0g</div>
                                        </div>
                                        <div class="col-3">
                                            <small class="text-muted">碳水</small>
                                            <div class="fw-bold small" th:text="${#numbers.formatDecimal(dish.carbohydrates, 1, 1)} + 'g'">0g</div>
                                        </div>
                                        <div class="col-3">
                                            <small class="text-muted">脂肪</small>
                                            <div class="fw-bold small" th:text="${#numbers.formatDecimal(dish.fat, 1, 1)} + 'g'">0g</div>
                                        </div>
                                    </div>
                                </div>

                                <!-- 标签 -->
                                <div class="mb-2">
                                    <span th:if="${dish.spiceLevel != null}"
                                          class="badge bg-warning me-1"
                                          th:text="${dish.spiceLevel.description}">辣度</span>
                                    <span th:if="${dish.cookingMethod != null}"
                                          class="badge bg-info me-1"
                                          th:text="${dish.cookingMethod.description}">烹饪方式</span>
                                </div>
                            </div>
                            <div class="card-footer bg-transparent">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <span class="fw-bold text-primary" th:text="'¥' + ${dish.price}">¥0</span>
                                        <small class="text-muted ms-1">/份</small>
                                    </div>
                                    <div class="btn-group btn-group-sm">
                                        <button class="btn btn-outline-primary"
                                                th:onclick="'addToCart(' + ${dish.id} + ', \'' + ${dish.name} + '\', ' + ${dish.calories} + ', ' + ${dish.price} + ')'">
                                            <i class="fas fa-plus"></i>
                                        </button>
                                        <a th:href="@{/meals/dish/{id}(id=${dish.id})}"
                                           class="btn btn-outline-secondary">
                                            <i class="fas fa-info"></i>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 分页 -->
                <div th:if="${dishPage.totalPages > 1}" class="d-flex justify-content-center mt-4">
                    <nav>
                        <ul class="pagination">
                            <li class="page-item" th:classappend="${!dishPage.hasPrevious() ? 'disabled' : ''}">
                                <a class="page-link" th:href="@{/meals(page=${dishPage.number - 1}, categoryId=${currentCategoryId}, keyword=${currentKeyword})}">
                                    <i class="fas fa-chevron-left"></i>
                                </a>
                            </li>
                            
                            <li th:each="pageNum : ${#numbers.sequence(0, dishPage.totalPages - 1)}" 
                                class="page-item" th:classappend="${pageNum == dishPage.number ? 'active' : ''}">
                                <a class="page-link" th:href="@{/meals(page=${pageNum}, categoryId=${currentCategoryId}, keyword=${currentKeyword})}" 
                                   th:text="${pageNum + 1}">1</a>
                            </li>
                            
                            <li class="page-item" th:classappend="${!dishPage.hasNext() ? 'disabled' : ''}">
                                <a class="page-link" th:href="@{/meals(page=${dishPage.number + 1}, categoryId=${currentCategoryId}, keyword=${currentKeyword})}">
                                    <i class="fas fa-chevron-right"></i>
                                </a>
                            </li>
                        </ul>
                    </nav>
                </div>
            </div>

            <!-- 侧边栏 -->
            <div class="col-lg-3">
                <!-- 今日点餐 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h6 class="mb-0">
                            <i class="fas fa-calendar-day me-2"></i>今日点餐
                        </h6>
                    </div>
                    <div class="card-body">
                        <div th:if="${todayOrders.empty}" class="text-center text-muted py-3">
                            <i class="fas fa-utensils fa-2x mb-2"></i>
                            <p class="mb-0">今日还没有点餐记录</p>
                        </div>
                        
                        <div th:unless="${todayOrders.empty}">
                            <div th:each="order : ${todayOrders}" class="border-bottom pb-2 mb-2">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <strong th:text="${order.dish.name}">菜品名称</strong>
                                        <div class="small text-muted">
                                            <span th:text="${order.mealType.description}">餐别</span> · 
                                            <span th:text="${order.portionSize}">1.0</span>份
                                        </div>
                                    </div>
                                    <small class="text-muted" th:text="${#numbers.formatDecimal(order.actualCalories, 0, 0)} + 'kcal'">0kcal</small>
                                </div>
                            </div>
                        </div>
                        
                        <div class="text-center mt-3">
                            <a th:href="@{/nutrition/dashboard}" class="btn btn-outline-primary btn-sm">
                                <i class="fas fa-chart-line me-1"></i>查看详情
                            </a>
                        </div>
                    </div>
                </div>

                <!-- 筛选器 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h6 class="mb-0">
                            <i class="fas fa-filter me-2"></i>筛选条件
                        </h6>
                    </div>
                    <div class="card-body">
                        <form id="filterForm">
                            <!-- 辣度 -->
                            <div class="mb-3">
                                <label class="form-label">辣度</label>
                                <select class="form-select form-select-sm" name="spiceLevel">
                                    <option value="">不限</option>
                                    <option value="NONE">不辣</option>
                                    <option value="MILD">微辣</option>
                                    <option value="MEDIUM">中辣</option>
                                    <option value="HOT">辣</option>
                                    <option value="VERY_HOT">很辣</option>
                                </select>
                            </div>
                            
                            <!-- 烹饪方式 -->
                            <div class="mb-3">
                                <label class="form-label">烹饪方式</label>
                                <select class="form-select form-select-sm" name="cookingMethod">
                                    <option value="">不限</option>
                                    <option value="FRIED">炒</option>
                                    <option value="STEAMED">蒸</option>
                                    <option value="BOILED">煮</option>
                                    <option value="GRILLED">烤</option>
                                    <option value="RAW">生食</option>
                                </select>
                            </div>
                            
                            <!-- 卡路里范围 -->
                            <div class="mb-3">
                                <label class="form-label">卡路里范围</label>
                                <div class="row">
                                    <div class="col-6">
                                        <input type="number" class="form-control form-control-sm" 
                                               name="minCalories" placeholder="最低">
                                    </div>
                                    <div class="col-6">
                                        <input type="number" class="form-control form-control-sm" 
                                               name="maxCalories" placeholder="最高">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="d-grid gap-2">
                                <button type="button" class="btn btn-primary btn-sm" onclick="applyFilters()">
                                    <i class="fas fa-search me-1"></i>应用筛选
                                </button>
                                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="clearFilters()">
                                    <i class="fas fa-times me-1"></i>清除筛选
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 购物车模态框 -->
    <div class="modal fade" id="cartModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-shopping-cart me-2"></i>购物车
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="cartContent">
                        <div class="text-center text-muted py-4">
                            <i class="fas fa-shopping-cart fa-3x mb-3"></i>
                            <p>购物车是空的</p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">继续选择</button>
                    <button type="button" class="btn btn-primary" onclick="submitOrder()" disabled id="submitOrderBtn">
                        <i class="fas fa-check me-1"></i>确认点餐
                    </button>
                </div>
            </div>
        </div>
    </div>

    <th:block layout:fragment="page-scripts">
        <script>
            let cart = [];
            
            // 搜索菜品
            function searchDishes() {
                const keyword = document.getElementById('searchInput').value;
                const url = new URL(window.location);
                if (keyword.trim()) {
                    url.searchParams.set('keyword', keyword);
                } else {
                    url.searchParams.delete('keyword');
                }
                url.searchParams.delete('page');
                window.location.href = url.toString();
            }
            
            // 回车搜索
            document.getElementById('searchInput').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    searchDishes();
                }
            });
            
            // 应用筛选
            function applyFilters() {
                const form = document.getElementById('filterForm');
                const formData = new FormData(form);
                const url = new URL(window.location);
                
                // 清除现有筛选参数
                ['spiceLevel', 'cookingMethod', 'minCalories', 'maxCalories'].forEach(param => {
                    url.searchParams.delete(param);
                });
                
                // 添加新的筛选参数
                for (let [key, value] of formData.entries()) {
                    if (value.trim()) {
                        url.searchParams.set(key, value);
                    }
                }
                
                url.searchParams.delete('page');
                window.location.href = url.toString();
            }
            
            // 清除筛选
            function clearFilters() {
                const url = new URL(window.location);
                ['spiceLevel', 'cookingMethod', 'minCalories', 'maxCalories'].forEach(param => {
                    url.searchParams.delete(param);
                });
                url.searchParams.delete('page');
                window.location.href = url.toString();
            }
            
            // 设置视图模式
            function setViewMode(mode) {
                // 这里可以实现网格/列表视图切换
                console.log('设置视图模式:', mode);
            }
            
            // 添加到购物车
            function addToCart(dishId, dishName, calories, price) {
                const existingItem = cart.find(item => item.dishId === dishId);
                
                if (existingItem) {
                    existingItem.quantity += 1;
                } else {
                    cart.push({
                        dishId: dishId,
                        dishName: dishName,
                        calories: calories,
                        price: price,
                        quantity: 1
                    });
                }
                
                updateCartDisplay();
                App.showMessage('success', `${dishName} 已添加到购物车`);
            }
            
            // 更新购物车显示
            function updateCartDisplay() {
                const cartCount = document.getElementById('cartCount');
                const cartContent = document.getElementById('cartContent');
                const submitBtn = document.getElementById('submitOrderBtn');
                
                if (cart.length === 0) {
                    cartCount.style.display = 'none';
                    cartContent.innerHTML = `
                        <div class="text-center text-muted py-4">
                            <i class="fas fa-shopping-cart fa-3x mb-3"></i>
                            <p>购物车是空的</p>
                        </div>
                    `;
                    submitBtn.disabled = true;
                } else {
                    const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
                    cartCount.textContent = totalItems;
                    cartCount.style.display = 'inline';
                    
                    let cartHtml = '<div class="list-group">';
                    cart.forEach(item => {
                        cartHtml += `
                            <div class="list-group-item d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="mb-1">${item.dishName}</h6>
                                    <small class="text-muted">${item.calories} kcal · ¥${item.price}</small>
                                </div>
                                <div class="d-flex align-items-center">
                                    <button class="btn btn-sm btn-outline-secondary" onclick="updateCartItem(${item.dishId}, -1)">-</button>
                                    <span class="mx-2">${item.quantity}</span>
                                    <button class="btn btn-sm btn-outline-secondary" onclick="updateCartItem(${item.dishId}, 1)">+</button>
                                    <button class="btn btn-sm btn-outline-danger ms-2" onclick="removeFromCart(${item.dishId})">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        `;
                    });
                    cartHtml += '</div>';
                    
                    cartContent.innerHTML = cartHtml;
                    submitBtn.disabled = false;
                }
            }
            
            // 更新购物车商品数量
            function updateCartItem(dishId, change) {
                const item = cart.find(item => item.dishId === dishId);
                if (item) {
                    item.quantity += change;
                    if (item.quantity <= 0) {
                        removeFromCart(dishId);
                    } else {
                        updateCartDisplay();
                    }
                }
            }
            
            // 从购物车移除商品
            function removeFromCart(dishId) {
                cart = cart.filter(item => item.dishId !== dishId);
                updateCartDisplay();
            }
            
            // 提交订单
            function submitOrder() {
                if (cart.length === 0) {
                    App.showMessage('error', '购物车是空的');
                    return;
                }
                
                // 这里应该显示餐别选择和份量调整界面
                // 暂时简化处理
                const mealType = getCurrentMealType();
                const orderRequests = cart.map(item => ({
                    dishId: item.dishId,
                    mealType: mealType,
                    portionSize: item.quantity
                }));
                
                fetch('/nutrition/orders/batch', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(orderRequests)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        App.showMessage('success', data.message);
                        cart = [];
                        updateCartDisplay();
                        bootstrap.Modal.getInstance(document.getElementById('cartModal')).hide();
                        // 刷新页面以更新今日点餐
                        setTimeout(() => {
                            window.location.reload();
                        }, 1000);
                    } else {
                        App.showMessage('error', data.message);
                    }
                })
                .catch(error => {
                    App.showMessage('error', '点餐失败，请稍后重试');
                    console.error('Error:', error);
                });
            }
            
            // 获取当前餐别
            function getCurrentMealType() {
                const hour = new Date().getHours();
                if (hour >= 7 && hour < 11) return 'BREAKFAST';
                if (hour >= 11 && hour < 15) return 'LUNCH';
                if (hour >= 17 && hour < 21) return 'DINNER';
                return 'SNACK';
            }
        </script>
    </th:block>
</body>
</html>
